'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigQq, IDifference, IUpdateQqConfigBody } from '@/interfaces';
import type { TBody } from '@/types';
import { updateQqConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { ConfigAdminContext } from '@/contexts/admin/config';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateConfigQq({ details }: { details: IConfigQq }) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    enable?: boolean;
    clientId?: string;
    clientSecret?: string;
    redirectUri?: string;
    state?: string;
  }>({
    enable: false,
    clientId: '',
    clientSecret: '*********',
    redirectUri: '',
    state: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();
  const context = useContext(ConfigAdminContext);

  const updateQqConfigMutation = useMutation(
    async (variables: TBody<IUpdateQqConfigBody>) => {
      await updateQqConfig(variables);
      await queryClient.invalidateQueries([
        '/configs',
        `/${context.updateItem?.id}`,
      ]);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        enable: details.enable,
        clientId: details.clientId || '',
        clientSecret: '*********',
        redirectUri: details.redirectUri || '',
        state: details.state || '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          enable: details.enable,
          clientId: details.clientId || '',
          clientSecret: '*********',
          redirectUri: details.redirectUri || '',
          state: details.state || '',
        },
        {
          enable: form.enable,
          clientId: form.clientId,
          clientSecret: form.clientSecret,
          redirectUri: form.redirectUri,
          state: form.state,
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'enable') {
      setForm({ ...form, enable: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateQqConfigMutation.mutateAsync({
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateQqConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <div className="vstack gap-4">
          <div>
            <p>温馨提示：</p>
            <ol className="text-muted">
              <li>
                QQ 应用申请：
                <a
                  target="_blank"
                  href="https://connect.qq.com/manage.html#/"
                  rel="noreferrer"
                >
                  https://connect.qq.com
                </a>
              </li>
              <li>
                回调地址
                <span className="text-muted">（替换 www.youdeyiwu.com）</span>
                ：https://www.youdeyiwu.com/qq
              </li>
              <li>应用接口：需要申请接口名称为：1.登录 + 2.unionid</li>
              <li>状态值：可填写应用拼音或英文名称</li>
            </ol>
          </div>

          <form onSubmit={onClickSave} className="vstack gap-4">
            <div>
              <label className="form-label">是否启用</label>
              <select
                name="enable"
                value={form.enable ? 'true' : 'false'}
                onChange={onChangeForm}
                className="form-select"
                aria-label="enable"
                placeholder="请选择是否启用 QQ 登录注册"
              >
                <option value="true">true</option>
                <option value="false">false</option>
              </select>
            </div>

            <div>
              <label className="form-label">应用 AppId</label>
              <input
                type="text"
                className="form-control"
                name="clientId"
                value={form.clientId}
                onChange={onChangeForm}
                aria-describedby="clientId"
                placeholder="请输入应用 AppId"
              />
            </div>

            <div>
              <label className="form-label">应用 AppKey</label>
              <input
                type="password"
                className="form-control"
                name="clientSecret"
                autoComplete="password"
                value={form.clientSecret}
                onChange={onChangeForm}
                aria-describedby="clientSecret"
                placeholder="请输入应用 AppKey"
              />
            </div>

            <div>
              <label className="form-label">回调地址</label>
              <input
                type="text"
                className="form-control"
                name="redirectUri"
                value={form.redirectUri}
                onChange={onChangeForm}
                aria-describedby="redirectUri"
                placeholder="请输入回调地址"
              />
            </div>

            <div>
              <label className="form-label">状态值</label>
              <input
                type="text"
                className="form-control"
                name="state"
                value={form.state}
                onChange={onChangeForm}
                aria-describedby="state"
                placeholder="请输入状态值"
              />
            </div>

            <button
              type="submit"
              disabled={updateQqConfigMutation.isLoading}
              className="btn btn-success w-25 my-4"
            >
              {updateQqConfigMutation.isLoading && (
                <span
                  className="spinner-border spinner-border-sm me-2"
                  role="status"
                  aria-hidden="true"
                ></span>
              )}
              更新
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
